package com.studyweb.service.impl;

import com.studyweb.pojo.entity.DataAnalysisQuestion;
import com.studyweb.mapper.DataAnalysisQuestionMapper;
import com.studyweb.service.DataAnalysisQuestionService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资料分析题目服务实现类
 */
@Service
@Slf4j
public class DataAnalysisQuestionServiceImpl implements DataAnalysisQuestionService {
    @Override
    @Transactional
    public boolean batchDeleteQuestions(List<Long> ids) {
        try {
            int rows = dataAnalysisQuestionMapper.batchDeleteByIds(ids);
            return rows > 0;
        } catch (Exception e) {
            log.error("批量删除资料分析题目失败：{}", e.getMessage(), e);
            throw new RuntimeException("批量删除资料分析题目失败", e);
        }
    }
    
    @Autowired
    private DataAnalysisQuestionMapper dataAnalysisQuestionMapper;
    
    @Override
    public Map<String, Object> getQuestions(int pageNum, int pageSize, String questionType, String difficulty, String category, String subCategory, String keyword, String orderBy, String orderType) {
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        
        // 处理排序参数
        if (orderBy != null && orderType != null) {
            PageHelper.orderBy(orderBy + " " + orderType);
        }
        
        // 使用selectQuestions方法进行分页查询，只需要传递查询条件参数
        List<DataAnalysisQuestion> questions = dataAnalysisQuestionMapper.selectQuestions(
            0, 0, questionType, difficulty, category, subCategory, keyword, orderBy, orderType);
        int total = dataAnalysisQuestionMapper.countQuestions(questionType, difficulty, category, subCategory, keyword);
        
        Map<String, Object> result = new HashMap<>();
        result.put("questions", questions);
        result.put("total", total);
        result.put("page", pageNum);
        result.put("pageSize", pageSize);
        result.put("totalPages", (int) Math.ceil((double) total / pageSize));
        
        return result;
    }
    
    @Override
    public DataAnalysisQuestion createQuestion(DataAnalysisQuestion question) {
        question.setCreateTime(LocalDateTime.now());
        question.setUpdateTime(LocalDateTime.now());
        question.setStatus(1);
        
        // 确保questionId为null，让数据库自动生成
        question.setQuestionId(null);
        
        int result = dataAnalysisQuestionMapper.insert(question);
        if (result > 0) {
            return question; // 返回包含ID的题目对象
        }
        return null;
    }
    
    @Override
    public DataAnalysisQuestion getQuestionById(Long id) {
        return dataAnalysisQuestionMapper.selectById(id);
    }
    
    @Override
    public boolean updateQuestion(DataAnalysisQuestion question) {
        question.setUpdateTime(LocalDateTime.now());
        int result = dataAnalysisQuestionMapper.updateById(question);
        return result > 0;
    }
    
    @Override
    public boolean deleteQuestion(Long id) {
        DataAnalysisQuestion existingQuestion = dataAnalysisQuestionMapper.selectById(id);
        if (existingQuestion == null) {
            return false;
        }
        
        int result = dataAnalysisQuestionMapper.deleteById(id);
        return result > 0;
    }
    
    @Override
    public List<DataAnalysisQuestion> getPracticeQuestions(int count, String difficulty, String category, String subCategory, String questionType) {
        // 默认按照question_id升序排列
        return getPracticeQuestions(count, difficulty, category, subCategory, questionType, "question_id", "asc");
    }
    
    // 添加一个新的重载方法，支持自定义排序
    public List<DataAnalysisQuestion> getPracticeQuestions(int count, String difficulty, String category, String subCategory, String questionType, String orderBy, String orderType) {
        // 如果count大于0，使用PageHelper进行分页
        if (count > 0) {
            PageHelper.startPage(1, count);
        }
        
        return dataAnalysisQuestionMapper.selectPracticeQuestions(0, difficulty, category, subCategory, questionType, orderBy, orderType);
    }
    
    @Override
    public Map<String, Object> submitAnswer(Map<String, Object> answerData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否包含answers数组
            if (!answerData.containsKey("answers")) {
                result.put("success", false);
                result.put("message", "缺少答案数据");
                return result;
            }
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> answers = (List<Map<String, Object>>) answerData.get("answers");
            
            int correctCount = 0;
            int totalCount = answers.size();
            
            // 处理每个答案
            for (Map<String, Object> answer : answers) {
                if (!answer.containsKey("questionId") || !answer.containsKey("userAnswer")) {
                    continue; // 跳过无效的答案
                }
                
                Long questionId = Long.valueOf(answer.get("questionId").toString());
                String userAnswer = answer.get("userAnswer") != null ? answer.get("userAnswer").toString() : "";
                
                DataAnalysisQuestion question = dataAnalysisQuestionMapper.selectById(questionId);
                if (question != null && question.getCorrectAnswer().equals(userAnswer)) {
                    correctCount++;
                }
                
                // TODO: 保存用户答题记录到数据库
            }
            
            // 计算得分
            double score = totalCount > 0 ? (double) correctCount / totalCount * 100 : 0;
            
            result.put("success", true);
            result.put("correctCount", correctCount);
            result.put("totalCount", totalCount);
            result.put("score", Math.round(score * 100.0) / 100.0);
            result.put("message", "答题完成");
            
            return result;
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "提交答案失败: " + e.getMessage());
            return result;
        }
    }
    
    @Override
    public Map<String, Object> getResults(int pageNum, int pageSize) {
        // TODO: 实现获取答题结果的逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("results", new java.util.ArrayList<>());
        result.put("total", 0);
        result.put("page", pageNum);
        result.put("pageSize", pageSize);
        result.put("totalPages", 0);
        
        return result;
    }
}